//
//  ChooseContactsViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/13.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "ChooseContactsViewController.h"
#import "ChooseContactsTableViewCell.h"
#import "DemoConfManager.h"
#import "GetHuanXinFriendListApi.h"
#import "FriendModel.h"
#import "GetHuanxinGroupUserListApi.h"

@interface ChooseContactsViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    EMGroup         *_group;
    BOOL            _isOwner;
    UITextField     *_subjectField;
}

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,strong) NSMutableArray *selectedContacts;
@property(nonatomic,copy) NSString *domain;

@end

@implementation ChooseContactsViewController
- (instancetype)initWithGroup:(EMGroup *)group
{
    self = [self init];
    if (self) {
        _group = group;
        NSString *loginUsername = [[EMClient sharedClient] currentUsername];
        _isOwner = [_group.owner isEqualToString:loginUsername];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    switch (_chooseType) {
        case AddMember:
        {
            
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                EMError *error = nil;
//                NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromServerWithError:&error];
//                if (!error)
//                {
//                    // 取出用户数组中不包括群组成员的部分
//                    NSArray *unselect = [userlist filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (SELF in %@)", _group.memberList]];
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self.dataSource removeAllObjects];
//                        [self.dataSource addObjectsFromArray:unselect];
//                        [self.tableView reloadData];
//                    });
//                }
//            });
            [SVProgressHUD showWithStatus:@"正在加载中..."];
            GetHuanXinFriendListApi *api = [[GetHuanXinFriendListApi alloc] init];
            [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                [SVProgressHUD dismiss];
                NSDictionary *dict = request.responseJSONObject;
                self.domain = dict[@"domain"];
                NSMutableArray *userList = [NSMutableArray arrayWithArray:[NSArray yy_modelArrayWithClass:[FriendModel class] json:dict[@"data"]]];
                for (NSString *uid in _group.memberList) {
                    for (FriendModel *model in userList)
                    {
                        if ([model.uid isEqualToString:uid])
                        {
                            [userList removeObject:model];
                        }
                    }
                }
                if (userList.count > 0)
                {
                    [self.dataSource removeAllObjects];
                    [self.dataSource addObjectsFromArray:userList];
                    [self.tableView reloadData];
                }
                
            } failure:nil];

        }
            break;
        case DeleteMember:
        {
//            [self.dataSource removeAllObjects];
//            [self.dataSource addObjectsFromArray:_group.memberList];
//            [self.tableView reloadData];
            [SVProgressHUD showWithStatus:@"正在加载中..."];
            GetHuanxinGroupUserListApi *api = [[GetHuanxinGroupUserListApi alloc] initWithDic:@{@"group_id":_group.groupId}];
            [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                NSDictionary *dict = request.responseJSONObject;
                self.domain = dict[@"domain"];
                [SVProgressHUD dismiss];
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[FriendModel class] json:dict[@"data"]];
                [self.dataSource addObjectsFromArray:array];
            
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            } failure:nil];
        }
            break;
        case VideoCall:
        {
//            EMError *error = nil;
//            NSArray *userList = [[EMClient sharedClient].contactManager getContactsFromServerWithError:&error];
            GetHuanXinFriendListApi *api = [[GetHuanXinFriendListApi alloc] init];
            [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                NSDictionary *dict = request.responseJSONObject;
                self.domain = dict[@"domain"];
                //            NSDictionary *dict = request.responseJSONObject[@"data"];
                NSArray *userList = [NSArray yy_modelArrayWithClass:[FriendModel class] json:dict[@"data"]];
                if (userList.count > 0)
                {
                    [self.dataSource removeAllObjects];
                    [self.dataSource addObjectsFromArray:userList];
                    [self.tableView reloadData];
                }

            } failure:nil];

        }
            break;
        default:
            break;
    }
}

- (void)setNavigationStyle
{
    switch (_chooseType) {
        case AddMember:
        {
            [self setNavigationBarTitle:@"添加成员"];
            [self setRightButtonTitle:@"添加" titleColor:[UIColor redColor] titleFont:fontCommonSize];
        }
            break;
        case DeleteMember:
        {
            [self setNavigationBarTitle:@"删除成员"];
            [self setRightButtonTitle:@"删除" titleColor:[UIColor redColor] titleFont:fontCommonSize];

        }
            break;
        case VideoCall:
        {
            [self setNavigationBarTitle:@"视频邀请"];
            [self setRightButtonTitle:@"完成" titleColor:rgba(143,157,189,1) titleFont:fontCommonSize];

        }
            break;
        default:
            break;
    }
}

#pragma mark --- 点击事件
- (void)onRightButtonClick:(id)sender
{
    if (self.selectedContacts.count == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择成员"];
    }
    else
    {
        switch (self.chooseType)
        {
            case AddMember:
            {
                [self addMember];
            }
                break;
            case DeleteMember:
            {
                [self deleteMember];
            }
                break;
            case VideoCall:
            {
                [self videoCall];
            }
                break;
                
            default:
                break;
        }
    }
 
}

- (void)videoCall
{
//    if (self.selectedContacts.count == 1)
//    {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_CALL object:@{@"chatter":self.selectedContacts.firstObject, @"type":[NSNumber numberWithInt:1]}];
//    }
//    else
//    {
        [[DemoConfManager sharedManager] createConferenceWithType:EMCallTypeVideo userNames:self.selectedContacts];
//    }
}

- (void)deleteMember
{
    [EMAlertView showAlertWithTitle:@"提示"
                            message:@"是否删除这些成员"
                    completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                        if (buttonIndex == 1) {
                            __weak typeof(self) weakSelf = self;
                            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                EMError *error = nil;
                                _group = [[EMClient sharedClient].groupManager removeOccupants:self.selectedContacts fromGroup:_group.groupId error:&error];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [weakSelf hideHud];
                                    if (!error) {
                                        [weakSelf.navigationController popViewControllerAnimated:YES];
                                    }
                                    else {
                                        [weakSelf showHint:@"您没有权限"];
//                                        [weakSelf showHint:error.errorDescription];
                                    }
                                    
                                });
                            });
                        }
                    } cancelButtonTitle:@"取消"
                  otherButtonTitles:@"确定", nil];
}

- (void)addMember
{
    [EMAlertView showAlertWithTitle:@"提示"
                            message:@"是否添加这些成员"
                    completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                        if (buttonIndex == 1) {
                            __weak typeof(self) weakSelf = self;
                            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                NSString *username = [[EMClient sharedClient] currentUsername];
                                NSString *messageStr = [NSString stringWithFormat:@"%@邀请你加入%@群组", username, _group.subject];
                                EMError *error = nil;
                                _group = [[EMClient sharedClient].groupManager addOccupants:self.selectedContacts toGroup:_group.groupId welcomeMessage:messageStr error:&error];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [weakSelf hideHud];
                                    if (!error) {
//                                        [weakSelf.tableView reloadData];
                                        [weakSelf.navigationController popViewControllerAnimated:YES];
                                    }
                                    else {
//                                        [weakSelf showHint:error.errorDescription];
                                        [weakSelf showHint:@"您没有权限"];
                                    }
                                    
                                });
                            });
                        }
                    } cancelButtonTitle:@"取消"
                  otherButtonTitles:@"确定", nil];
}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(180);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChooseContactsTableViewCell *cell = [ChooseContactsTableViewCell cellWithTableView:tableView forIndexPath:indexPath];
//    cell.iconImageView.image = imageWithName(@"head1");
    FriendModel *model = self.dataSource[indexPath.section];
    NSString *url = [NSString stringWithFormat:@"%@%@",self.domain,model.image];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:imageWithName(@"icon_head")];
    [cell setFriendWithModel:model];
    if ([model.nickname isEqualToString:@""])
    {
        cell.titleLabel.text = @"我的机器人";
        cell.iconImageView.image = imageWithName(@"robot_head");
    }
    BOOL sign = NO;
    for (NSString *name in self.selectedContacts)
    {
        if ([name isEqualToString:model.uid])
        {
            cell.selectedButton.selected = YES;
            sign = YES;
            break;
        }
        else
        {
            sign = NO;
        }
    }
    if (!sign)
    {
        cell.selectedButton.selected = NO;
    }
//    cell.titleLabel.text = model.nickname;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    FriendModel *model = self.dataSource[indexPath.section];
    BOOL sign = NO;
    for (NSString *name in self.selectedContacts)
    {
        if ([name isEqualToString:model.uid])
        {
            [self.selectedContacts removeObject:model.uid];
            [self.tableView reloadData];
            sign = YES;
            break;
        }
        else
        {
            sign = NO;
        }
    }
    if (!sign)
    {
        [self.selectedContacts addObject:model.uid];
        [self.tableView reloadData];
    }
}

#pragma mark --- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        [superView addSubview:_tableView];
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (NSMutableArray *)selectedContacts
{
    if(!_selectedContacts)
    {
        _selectedContacts = [[NSMutableArray alloc]init];
    }
    return _selectedContacts;
}


#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(262));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
